<template>
  <FilterNavbar>
    <template #center>
      <view class="navbar-title"> {{ pageTitle }} </view>
    </template>
  </FilterNavbar>

  <ve-form ref="ve_form" :model="form" :rules="rules" style="padding: 24rpx">
    <ve-card title="个人信息" type="none" fold v-model:initFold="foldStatus.fold1">
      <ve-form-item label="姓名" prop="memberName" required labelPosition="top">
        <ve-input v-model="form.memberName" type="textarea" :maxlength="50" :autoHeight="true" placeholder="请输入" />
      </ve-form-item>

      <ve-form-item label="手机号" prop="phone" required>
        <ve-input v-model="form.phone" placeholder="请输入" />
      </ve-form-item>

      <ve-form-item label="性别">
        <ve-picker-inline v-model="form.sex" placeholder="请选择性别" :range="dict.sexMap"> </ve-picker-inline>
      </ve-form-item>

      <ve-form-item label="所属企业" :borderBottom="false">
        <remote-select
          type="client"
          v-model="form.clientId"
          :params="{ oldId: form.clientId ? form.clientId : undefined }"
          :label="form.clientName"
          @change="changeClient"
        />
      </ve-form-item>
      <block v-if="record">
        <ve-cell label="电子合同认证状态">
          <text :class="'contract-status_' + record.ecAuthenticationStatus">{{ record.ecAuthenticationStatusName }}</text>
        </ve-cell>
        <view v-if="record.ecAuthenticationStatus == 0" class="status_reason c1 fw400 fs30">
          <view>原因：</view>
          <view v-if="record.authenticationFailedReason">{{ record.authenticationFailedReason || '-' }}</view>
        </view>
      </block>
    </ve-card>
    <ve-card title="紧急联系人" type="none" fold v-model:initFold="foldStatus.fold2">
      <ve-form-item label="姓名">
        <ve-input v-model="form.emergencyContactName" placeholder="请输入" />
      </ve-form-item>

      <ve-form-item label="手机号" :borderBottom="false">
        <ve-input v-model="form.emergencyContactPhone" placeholder="请输入" />
      </ve-form-item>
    </ve-card>

    <ve-card title="证件上传" type="none" fold v-model:initFold="foldStatus.fold3">
      <view class="flex_img">
        <view class="ui_driving_up" :style="cardFrontBackgroundImgStyle">
          <image :src="idCardFrontFileId.openUrl" @click="preview('idCardFrontFileId')" />
          <view class="ui_tip" v-if="idCardFrontFileId.openUrl" @click="handleUpload('idCardFrontFileId')">重新上传</view>
        </view>
        <view class="ui_driving_down" :style="cardBackBackgroundImgStyle">
          <image :src="idCardBackFileId.openUrl" @click="preview('idCardBackFileId')" />
          <view class="ui_tip" v-if="idCardBackFileId.openUrl" @click="handleUpload('idCardBackFileId')">重新上传</view>
        </view>
      </view>
      <view style="height: 2rpx; background: rgba(216, 216, 216, 0.3); margin-top: 32rpx"></view>
      <ve-form-item label="证件类型">
        <ve-picker-inline v-model="form.cardType" placeholder="请选择" :range="dict.cardTypeMap"> </ve-picker-inline>
      </ve-form-item>
      <ve-form-item label="证件号">
        <ve-input v-model="form.cardNumber" placeholder="请输入"> </ve-input>
      </ve-form-item>
      <ve-form-item label="证件住址">
        <ve-input v-model="form.cardAddress" placeholder="请输入" maxlength="100"> </ve-input>
      </ve-form-item>
      <ve-form-item label="证件到期日" :borderBottom="false">
        <ve-date-picker mode="date" v-model="form.identityExpireTime" @confirm="dateconfirm('ID')" title="时间"></ve-date-picker>
        <checkbox-group @change="changeidCardLongFlag($event)">
          <checkbox
            value="1"
            color="#3072F6"
            style="transform: scale(0.7); margin-right: 30rpx"
            class="checkbox"
            :checked="form.identityLong == 0 || !form.identityLong ? false : true"
            ><span
              style="
                font-size: 21.4px;
                font-family: PingFang SC-Regular, PingFang SC;
                font-weight: 400;
                color: #1d2129;
                margin-right: -30px;
              "
              >长期</span
            >
          </checkbox>
        </checkbox-group>
      </ve-form-item>
    </ve-card>

    <ve-card title="上传驾驶证" type="none" fold v-model:initFold="foldStatus.fold4">
      <view class="flex_img">
        <view class="ui_driving_up" :style="driverCardFrontBackgroundStyle">
          <image :src="driverCardFrontFileId.openUrl" @click="preview('driverCardFrontFileId')" />
          <view class="ui_tip" v-if="driverCardFrontFileId.openUrl" @click="handleUpload('driverCardFrontFileId')">重新上传</view>
        </view>
        <view class="ui_driving_down" :style="driverCardBackBackgroundStyle">
          <image :src="driverCardBackFileId.openUrl" @click="preview('driverCardBackFileId')" />
          <view class="ui_tip" v-if="driverCardBackFileId.openUrl" @click="handleUpload('driverCardBackFileId')">重新上传</view>
        </view>
      </view>
      <view style="height: 2rpx; background: rgba(216, 216, 216, 0.3); margin-top: 32rpx"></view>
      <ve-form-item label="驾驶证号">
        <ve-input v-model="form.driverNumber" placeholder="请输入"> </ve-input>
      </ve-form-item>
      <ve-form-item label="驾驶证到期日" :borderBottom="false">
        <ve-date-picker mode="date" v-model="form.driverExpireTime" @confirm="dateconfirm('DRIVER')" title="时间"></ve-date-picker>
        <checkbox-group @change="changedirverLongFlag($event)">
          <checkbox
            :value="form.dirverLongFlag"
            color="#3072F6"
            style="transform: scale(0.7); margin-right: 30rpx"
            class="checkbox"
            :checked="form.driverLong == 0 || !form.driverLong ? false : true"
            ><span
              style="
                font-size: 21.4px;
                font-family: PingFang SC-Regular, PingFang SC;
                font-weight: 400;
                color: #1d2129;
                margin-right: -30px;
              "
              >长期</span
            >
          </checkbox>
        </checkbox-group>
      </ve-form-item>
    </ve-card>
    <ve-bottom-box size="mini">
      <ve-button type="primary" size="long" :loading="saveLoading" @click="handleSave">确认</ve-button>
    </ve-bottom-box>
  </ve-form>
</template>

<script setup>
  // #ifdef APP-PLUS
  import permision from '@/utils/permissionCheck/permission.js'
  // #endif
  import { ref, nextTick } from 'vue'
  import { onShow, onLoad } from '@dcloudio/uni-app'
  import { packagedUploadFile } from '@/utils/upload-tool'
  import {
    createOrUpdateMember,
    memberDetail,
    IdCardFrontOCR,
    IdCardBackOCR,
    driverCardFrontOCR,
    driverCardBackOCR,
    getFileInfo,
  } from '@/api/market/member'
  import useFormFold from '@/hooks/useFormFold'
  import { usePageDict } from '@/hooks/useDict'
  import FilterNavbar from '@/components/FilterNavbar'
  import { userStore } from '@/stores'

  const userInfoStore = userStore()
  userInfoStore.setEpDetail(false)

  const dict = usePageDict('memberDict')
  const form = ref({ cardType: 0 })

  const record = ref({})

  const saveLoading = ref(false)
  const pageTitle = ref('新增个人会员')
  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['memberName', 'phone'],
    },
    {
      key: 'fold2',
      props: [],
    },
    {
      key: 'fold3',
      props: [],
    },
    {
      key: 'fold4',
      props: [],
    },
  ])

  const cardFrontBackgroundImgStyle = ref('background-image: url("../../../../../static/images/document_front.png")')

  const cardBackBackgroundImgStyle = ref('background-image: url("../../../../../static/images/document_back.png")')

  const driverCardFrontBackgroundStyle = ref('background-image: url("../../../../../static/images/driver_card_front.png")')

  const driverCardBackBackgroundStyle = ref('background-image: url("../../../../../static/images/driver_card_back.png")')

  const idCardFrontFileId = ref({ openUrl: '' })

  const idCardBackFileId = ref({ openUrl: '' })

  const driverCardFrontFileId = ref({ openUrl: '' })

  const driverCardBackFileId = ref({ openUrl: '' })

  const changeClient = (_, option = {}) => {
    form.value.clientName = option.clientName
  }

  const rules = ref({
    memberName: {
      required: true,
      message: '请输入姓名',
    },
    phone: {
      required: true,
      message: '请输入手机号',
    },
  })

  const ve_form = ref(null)
  const handleSave = () => {
    // 表单验证
    saveLoading.value = true
    ve_form.value.validate((valid, errors) => {
      if (valid) {
        console.log('验证通过')
        // if(pageTitle.value == '编辑个人会员' &&(record.value.ecAuthenticationStatus == 0 || record.value.ecAuthenticationStatus == 1 || record.value.ecAuthenticationStatus == 2)){
        //   if(form.value.phone != record.value.phone){

        //   }else if(form.value.memberName != record.value.memberName){

        //   }else if(form.value.memberName != record.value.memberName && form.value.phone != record.value.phone){

        //   }else{
        //     createOrUpdateMemberFn()
        //   }
        // }else{
        //   createOrUpdateMemberFn()
        // }
        if (
          pageTitle.value == '编辑个人会员' &&
          form.value.phone != record.value.phone &&
          (record.value.ecAuthenticationStatus == 0 || record.value.ecAuthenticationStatus == 1 || record.value.ecAuthenticationStatus == 2)
        ) {
          // 电子合同增加: 认证成功、认证失败、认证中时，点击确认时需提示商户
          uni.showModal({
            title: '提示',
            content: '个人会员已发起电子合同认证，如修改电话号码，下次签署合同时，需重新认证，是否修改手机号？',
            success: function (res) {
              if (res.confirm) {
                createOrUpdateMemberFn()
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            },
          })
        } else if (
          pageTitle.value == '编辑个人会员' &&
          form.value.memberName != record.value.memberName &&
          (record.value.ecAuthenticationStatus == 0 || record.value.ecAuthenticationStatus == 1 || record.value.ecAuthenticationStatus == 2)
        ) {
          // 电子合同增加: 认证成功、认证失败、认证中时，点击确认时需提示商户
          uni.showModal({
            title: '提示',
            content: '个人会员已发起电子合同认证，如修改姓名，下次签署合同时，需重新认证，是否修改姓名？',
            success: function (res) {
              if (res.confirm) {
                createOrUpdateMemberFn()
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            },
          })
        } else if (
          pageTitle.value == '编辑个人会员' &&
          form.value.memberName != record.value.memberName &&
          form.value.phone != record.value.phone &&
          (record.value.ecAuthenticationStatus == 0 || record.value.ecAuthenticationStatus == 1 || record.value.ecAuthenticationStatus == 2)
        ) {
          // 电子合同增加: 认证成功、认证失败、认证中时，点击确认时需提示商户
          uni.showModal({
            title: '提示',
            content: '个人会员已发起电子合同认证，如修改姓名和电话号码，下次签署合同时，需重新认证，是否修改姓名和手机号？',
            success: function (res) {
              if (res.confirm) {
                createOrUpdateMemberFn()
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            },
          })
        } else {
          createOrUpdateMemberFn()
        }
      } else {
        saveLoading.value = false
        foldValidate(errors)
        console.log('验证失败', errors)
      }
    })
  }

  const createOrUpdateMemberFn = () => {
    const params = {
      ...form.value,
    }
    if (form.value.emergencyContactPhone == '') {
      params.emergencyContactPhone = null
    }
    createOrUpdateMember(params)
      .then((res) => {
        saveLoading.value = false
        if (res.code == 200) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          uni.$emit('refreshData')
          uni.navigateBack({
            delta: 1,
          })
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none',
          })
        }
      })
      .catch(() => {
        saveLoading.value = false
      })
  }

  const getDetail = async (id) => {
    const res = await memberDetail({ id: id.id })
    if (res.code === 200) {
      const data = res.result
      form.value = data
      record.value = data
      if (data.idCardFrontFileId) {
        getFileInfoApi('idFront', data.idCardFrontFileId)
      }
      if (data.idCardReverseFileId) {
        getFileInfoApi('idBack', data.idCardReverseFileId)
      }
      if (data.driverFrontFileId) {
        getFileInfoApi('driverFront', data.driverFrontFileId)
      }
      if (data.driverReverseFileId) {
        getFileInfoApi('driverBack', data.driverReverseFileId)
      }
    }
  }

  const getFileInfoApi = (way, id) => {
    if (id) {
      getFileInfo({ id: id }).then((res) => {
        if (res.code == 200) {
          let result = res.result
          if (way == 'idFront') {
            idCardFrontFileId.value.openUrl = result.openUrl
          }
          if (way == 'idBack') {
            idCardBackFileId.value.openUrl = result.openUrl
          }
          if (way == 'driverFront') {
            driverCardFrontFileId.value.openUrl = result.openUrl
          }
          if (way == 'driverBack') {
            driverCardBackFileId.value.openUrl = result.openUrl
          }
        }
      })
    }
  }

  const handleUpload = (way) => {
    // #ifdef APP-PLUS
    permision.premissionCheck('CAMERA_EXTERNAL_STORAGE').then((result1) => {
      console.log('result1', result1)
      if (result1 == 1) {
        // #endif
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['camera', 'album'],
          success: (res) => {
            console.log(res)
            let imgPath = res.tempFilePaths[0]
            let resSize = res.tempFiles[0].size
            if (resSize > 2291456) {
              uni.showToast({
                title: '上传图片大小不能超过2MB',
                icon: 'none',
              })
              return
            }
            console.log(imgPath)
            console.log(getApp().globalData.requestUrl + '/uploadFile/commonUpload')
            //  handleImgSuccess(way, imgPath)
            packagedUploadFile({
              filePath: imgPath,
              success: (res) => {
                const _data = JSON.parse(res.data)
                if (_data.code == 200) {
                  handleImgSuccess(way, _data.result[0])
                } else {
                  uni.showToast({
                    title: _data.resultMsg ? _data.resultMsg : '网络异常,请稍后再试',
                    icon: 'none',
                  })
                  handleImgError(way, imgPath)
                }
              },
              fail: (err) => {
                handleImgError(way, imgPath)
                uni.showToast({
                  title: '网络异常,请稍后再试',
                  icon: 'none',
                })
              },
              complete: () => {
                // #ifdef APP-PLUS
                uni.removeSavedFile({
                  filePath: imgPath,
                })
                // #endif
              },
            })
          },
        })
        // #ifdef APP-PLUS
      }
    })
    // #endif
  }
  /**
   * 上传失败
   */
  const handleImgError = (way, imgPath) => {
    console.log(way, imgPath)
    // 身份证正面
    if (way == 'idCardFrontFileId') {
      idCardFrontFileId.value.openUrl = imgPath
    }
    // 身份证反面
    if (way == 'idCardBackFileId') {
      idCardBackFileId.value.openUrl = imgPath
    }

    // 驾驶证正面
    if (way == 'driverCardFrontFileId') {
      driverCardFrontFileId.value.openUrl = imgPath
    }
    // 驾驶证反面
    if (way == 'driverCardBackFileId') {
      driverCardBackFileId.value.openUrl = imgPath
    }
  }
  /**
   * 上传成功
   */
  const handleImgSuccess = (way, item) => {
    // 身份证正面
    if (way == 'idCardFrontFileId') {
      form.value.idCardFrontFileId = item.fileIdStr
      idCardFrontFileId.value.openUrl = item.openUrl
      handleOCR(way, item.fileIdStr)
    }
    // 身份证反面
    if (way == 'idCardBackFileId') {
      form.value.idCardReverseFileId = item.fileIdStr
      idCardBackFileId.value.openUrl = item.openUrl
      handleOCR(way, item.fileIdStr)
    }
    // 驾驶证正面
    if (way == 'driverCardFrontFileId') {
      form.value.driverFrontFileId = item.fileIdStr
      driverCardFrontFileId.value.openUrl = item.openUrl
      handleOCR(way, item.fileIdStr)
    }
    // 驾驶证反面
    if (way == 'driverCardBackFileId') {
      form.value.driverReverseFileId = item.fileIdStr
      driverCardBackFileId.value.openUrl = item.openUrl
      handleOCR(way, item.fileIdStr)
    }
  }

  /**
   * OCR自动识别
   */
  const handleOCR = (way, fileId) => {
    // 商户后台配置开关关闭，则不执行ocr识别
    if (!userInfoStore.epOcrSwitch) {
      return false
    }
    let fetch
    if (way == 'idCardFrontFileId') {
      fetch = IdCardFrontOCR
    }
    if (way == 'idCardBackFileId') {
      fetch = IdCardBackOCR
    }
    if (way == 'driverCardFrontFileId') {
      fetch = driverCardFrontOCR
    }
    if (way == 'driverCardBackFileId') {
      fetch = driverCardBackOCR
    }
    fetch({ fileId: fileId }).then((res) => {
      if (res.code == 200) {
        let result = res.result
        nextTick(() => {
          // 身份证正面 - 更新身份证号/地址
          if (way == 'idCardFrontFileId') {
            form.value.memberName = result.name
            form.value.cardNumber = result.number
            form.value.cardAddress = result.address
          }
          // 身份证反面 - 更新证件到期日
          if (way == 'idCardBackFileId') {
            if (result.endDate == '长期') {
              form.value.identityExpireTime = undefined
              form.value.identityLong = 1
            } else {
              form.value.identityExpireTime = result.endDate
              form.value.identityLong = 0
            }
          }
          // 驾驶证正面 - 更新驾驶证号码、驾驶证到期日
          if (way == 'driverCardFrontFileId') {
            form.value.driverNumber = result.number
            if (result.validEndDate == '长期') {
              form.value.driverExpireTime = undefined
              form.value.driverLong = 1
            } else {
              form.value.driverExpireTime = result.validEndDate
              form.value.driverLong = 0
            }
          }
        })
      } else {
        uni.showToast({
          title: res.message,
          icon: 'none',
        })
      }
    })
  }

  // 选择 证件到期日 - 清空长期
  const dateconfirm = (e) => {
    console.log(e)
    if (e == 'ID') {
      form.value.identityLong = 0
    } else {
      form.value.driverLong = 0
    }
  }
  // 选择 身份证是否长期
  const changeidCardLongFlag = (e) => {
    if (e.detail && e.detail.value.length) {
      form.value.identityLong = 1
      form.value.identityExpireTime = undefined
    } else {
      form.value.identityLong = 0
    }
  }

  // 选择 驾驶证是否长期
  const changedirverLongFlag = (e) => {
    if (e.detail && e.detail.value.length) {
      form.value.driverLong = 1
      form.value.driverExpireTime = undefined
    } else {
      form.value.driverLong = 0
    }
  }

  const preview = (way) => {
    let url
    if (way == 'idCardFrontFileId') {
      url = idCardFrontFileId.value.openUrl
    }
    // 身份证反面
    else if (way == 'idCardBackFileId') {
      url = idCardBackFileId.value.openUrl
    }
    // 驾驶证正面
    else if (way == 'driverCardFrontFileId') {
      url = driverCardFrontFileId.value.openUrl
    }
    // 驾驶证反面
    else if (way == 'driverCardBackFileId') {
      url = driverCardBackFileId.value.openUrl
    }
    // 有去预览没有去上传
    if (url) {
      uni.previewImage({
        current: 0, // 当前显示图片的
        urls: [url],
      })
      return
    }
    handleUpload(way)
  }

  onLoad((id) => {
    console.log(id)
    if (id.id) {
      pageTitle.value = '编辑个人会员'
      getDetail(id)
    }
  })
</script>

<style lang="less" scoped>
  page {
    background: #f7f8fa;
  }
  .flex_img {
    display: flex;
    justify-content: space-around;
    margin-top: 32rpx;
  }
  .ui_driving_up {
    position: relative;
    width: 284rpx;
    height: 184rpx;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    overflow: hidden;
    border-radius: 16rpx;
  }
  .ui_driving_up image {
    background-repeat: no-repeat;
    background-size: 100% 100%;
    width: 100%;
    height: 100%;
  }
  .ui_driving_down {
    position: relative;
    width: 284rpx;
    height: 184rpx;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    overflow: hidden;
    border-radius: 16rpx;
  }
  .ui_driving_down image {
    background-repeat: no-repeat;
    background-size: 100% 100%;
    width: 100%;
    height: 100%;
  }
  .ui_tip {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    text-align: center;
    height: 56rpx;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 0px 0px 16rpx 16rpx;
    font-size: 24rpx;
    font-weight: 400;
    color: #ffffff;
    line-height: 56rpx;
  }

  ::v-deep .uni-checkbox-wrapper span {
    font-size: 28rpx;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #1d2129;
  }

  .contract-status_-1 {
    color: #f53f3f;
  }
  .contract-status_0 {
    color: #f53f3f;
  }
  .contract-status_1 {
    color: #00b42a;
  }
  .contract-status_2 {
    color: #ff7d00;
  }
  .status_reason {
    background-color: #f7f8fa;
    padding: 24rpx;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    view:nth-child(1) {
      min-width: 80rpx;
    }
    view:nth-child(2) {
      flex: 1;
    }
  }
</style>
